import pandas as pd
from sklearn.preprocessing import StandardScaler
from statsmodels.stats.outliers_influence import variance_inflation_factor

# 读取数据
df = pd.read_excel("D:\Lenovo\Desktop\云南大学\毕业设计\毕设数据\输出数据\excel\countyzhujiang_Factors_2010_空间连接_TableToExcel.xlsx")

# 分离因变量和自变量
dependent_column = ['总碳排10','Burn10NEW1','Crop10CB','Urban10CB']
X=df.drop(dependent_column,axis=1)
y = df[dependent_column]

# 标准化自变量
scaler = StandardScaler()
X_scaled = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)

# 添加截距项
X_scaled_with_const = X_scaled.copy()
X_scaled_with_const['const'] = 1

# 计算VIF
vif_data = pd.DataFrame()
vif_data['Variable'] = X_scaled_with_const.columns
vif_data['VIF'] = [variance_inflation_factor(X_scaled_with_const.values, i) for i in range(X_scaled_with_const.shape[1])]

# 移除截距项的结果
vif_data = vif_data[vif_data['Variable'] != 'const']

print("各变量的VIF值：")
print(vif_data)

# 判断高VIF变量
# high_vif_threshold = 10
# high_vif = vif_data[vif_data['VIF'] > high_vif_threshold]
# print(f"\nVIF超过{high_vif_threshold}的变量：")
# print(high_vif)